package com.RuiJi.controller;

import com.RuiJi.entity.Category;
import com.RuiJi.entity.Dish;
import com.RuiJi.entity.DishFlavor;
import com.RuiJi.entity.dto.DishDto;
import com.RuiJi.service.CategoryService;
import com.RuiJi.service.DishFlavorService;
import com.RuiJi.service.DishService;
import com.RuiJi.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Twinkle
 * @PACKAGE_NAME: com.RuiJi.controller
 * @NAME: DishController
 * @USER: Twinkle
 * @DATE: 2023/4/8
 * @TIME: 11:46
 * @YEAR: 2023
 * @MONTH: 04
 */
@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页操作
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);

        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(dishPage, dtoPage, "records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) ->
        {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);


            //分类ID
            Long categoryId = item.getCategoryId();

            //根据ID查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();

                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //清理所有菜品缓存
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
      //清理部分缓存
        String keys =  "dish_"+dishDto.getCategoryId()+"_1";
        Set keys1 = redisTemplate.keys(keys);
        redisTemplate.delete(keys1);
        dishService.saveWithFlavor(dishDto);
        return R.success("新增成功");
    }

    /**
     * 根据ID回显菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品缓存
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
        String keys =  "dish_"+dishDto.getCategoryId()+"_1";
        Set keys1 = redisTemplate.keys(keys);
        redisTemplate.delete(keys1);
        return R.success("修改成功");
    }

    /**
     * 查询分类菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从Redis中获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        } else {
            //条件构造器，条件name和categoryId和status（price那些条件始终没需求就不做条件），根据更新时间排序
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            //queryWrapper.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
            queryWrapper.eq(null != dish.getCategoryId(), Dish::getCategoryId, dish.getCategoryId());
            //查询条件，状态为1（起售状态）的菜品
            queryWrapper.eq(Dish::getStatus, 1);
            queryWrapper.orderByAsc(Dish::getSort);
            //条件查询到菜品列表
            List<Dish> dishs = dishService.list(queryWrapper);
            //对list每个元素加工，设置分类和味道信息，返回成dto，
            dishDtos = dishs.stream().map(item -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item, dishDto);
                Category category = categoryService.getById(item.getCategoryId());
                if (category != null) {
                    dishDto.setCategoryName(category.getName());
                }
                LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DishFlavor::getDishId, item.getId());
                dishDto.setFlavors(dishFlavorService.list(wrapper));
                return dishDto;
            }).collect(Collectors.toList());
            //不存在查询数据库 缓存至Redis
            redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);
            return R.success(dishDtos);
        }
    }

    /**
     * 修改状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Dish::getId, ids);
        for (Dish dish : dishService.list(queryWrapper)) {
            if (dish != null) {
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("菜品状态修改成功");
    }
}
